package com.stream.utils.schedule;

import com.alibaba.fastjson.JSON;
import com.stream.model.entity.ScheduleJobEntity;
import com.stream.utils.Constant;
import com.stream.utils.RRException;
import org.quartz.*;

/**
 * Created by Stream on 2017/7/2.
 */
public class ScheduleUtils {
    private static final String JOB_NAME = "TASK_";

    /**
     * 获取触发器key
     * @param jobId
     * @return
     */
    public static TriggerKey getTriggerKey(Long jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobkey
     * @param jobId
     * @return
     */
    public static JobKey getJobKey(Long jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     * @param scheduler
     * @param jobId
     * @return
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
        try {
            return ((CronTrigger) scheduler.getTrigger(getTriggerKey(jobId)));
        } catch (SchedulerException e) {
            throw new RRException("获取定时任务CronTrigger出现异常", e);
        }
    }


    /**
     * 创建定时任务
     * @param scheduler
     * @param job
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity job) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(job.getJobId())).build();
            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, JSON.toJSONString(job));

            //表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()).withMisfireHandlingInstructionDoNothing();

            //用新的 CronExpress 表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(job.getJobId())).withSchedule(cronScheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);

            //暂停任务
            if (job.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()) {
                pause(scheduler, job.getJobId());
            }
        } catch (SchedulerException e) {
            throw new RRException("创建定时任务失败", e);
        }

    }


    /**
     * 更新定时任务
     * @param scheduler
     * @param job
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJobEntity job) {
        try {
            TriggerKey triggerKey = getTriggerKey(job.getJobId());
            //表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()).withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = getCronTrigger(scheduler, job.getJobId());

            //按新的 cronExpress 表达式重新构建 trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();

            //参数
            trigger.getJobDataMap().put(ScheduleJobEntity.JOB_PARAM_KEY, JSON.toJSONString(job));

            scheduler.rescheduleJob(triggerKey, trigger);

            //暂停任务
            if (job.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()) {
                pause(scheduler, job.getJobId());
            }
        } catch (SchedulerException e) {
            throw new RRException("更新定时任务失败.",e);
        }
    }

    /**
     * 立即执行任务
     * @param scheduler
     * @param job
     */
    public static void run(Scheduler scheduler, ScheduleJobEntity job) {
        try {
            //参数
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put(ScheduleJobEntity.JOB_PARAM_KEY, JSON.toJSONString(job));
            scheduler.triggerJob(getJobKey(job.getJobId()), jobDataMap);
        } catch (SchedulerException e) {
            throw new RRException("立即执行定时任务失败.",e);
        }

    }

    /**
     * 暂停任务
     * @param scheduler
     * @param jobId
     */
    public static void pause(Scheduler scheduler, Long jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RRException("暂停定时任务失败.",e);
        }
    }

    /**
     * 恢复定时任务
     * @param scheduler
     * @param jobId
     */
    public static void resume(Scheduler scheduler, Long jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RRException("恢复定时任务失败.",e);
        }
    }

    /**
     * 删除定时任务
     * @param scheduler
     * @param jobId
     */
    public static void delete(Scheduler scheduler, Long jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RRException("删除定时任务失败.",e);
        }
    }
}
